package com.winit.cloudlink.mgmt.task;

import com.google.common.collect.Maps;
import lombok.Data;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.Date;
import java.util.Map;

import static com.winit.cloudlink.common.utils.ObjectUtils.isSimpleValueType;
import static org.apache.commons.lang3.StringUtils.isBlank;

@Data
public class Task implements Serializable {
    private String id;

    private String name;

    private String type;

    private Status status;

    private String error;

    private Date created;

    private Date started;

    private Date ended;

    private Map<String, String> params = Maps.newHashMap();


    public Task() {
    }

    public String getParameter(String name) {
        return params.get(name);
    }

    public String getParameter(String name, String defaultValue) {
        String value = extractParameterValue(name);
        return value == null ? defaultValue : value;
    }

    public boolean getParameter(String name, boolean defaultValue) {
        String value = extractParameterValue(name);
        return value == null ? defaultValue : Boolean.valueOf(value).booleanValue();
    }

    public int getParameter(String name, int defaultValue) {
        String value = extractParameterValue(name);
        return value == null ? defaultValue : Integer.valueOf(value).intValue();
    }

    public long getParameter(String name, long defaultValue) {
        String value = extractParameterValue(name);
        return value == null ? defaultValue : Long.valueOf(value).longValue();
    }

    public Date getParameter(String name, Date defaultValue) {
        String value = extractParameterValue(name);
        return value == null ? defaultValue : new Date(Long.valueOf(value));
    }


    public void addParameter(String name, Object value) {
        Assert.notNull(value, "value must not be null");
        if (!isSimpleValueType(value.getClass())) {
            throw new IllegalArgumentException("value must be simple java type");
        }
        params.put(name, value.toString());
    }


    private String extractParameterValue(String name) {
        String value = getParameter(name);
        if (value == null) {
            return null;
        }
        value = value.trim();
        if (isBlank(value)) {
            return null;
        }
        return value;
    }
}